﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace JsonUsage
{
    /// <summary>
    /// http://www.cnblogs.com/yanweidie/p/4605212.html
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
        Start:
            Console.WriteLine("选择一个指令,然后继续");
            Console.WriteLine("[0]:退出;");
            Console.WriteLine("[1]:Datatable序列化与反序列化");
            Console.WriteLine("[2]:忽略某些属性");
            Console.WriteLine("[3]:动态决定属性是否序列化");

            string[] list = new string[] { "0", "1", "2", "3" };
            string input = Console.ReadLine();
            if (list.Where(o => o.Equals(input)).FirstOrDefault() != null)
            {
                Dictionary<string, Action> dict = new Dictionary<string, Action>()
                {
                    {"0",()=> {Environment.Exit(0); }},
                    {"1",()=> Datatable()},
                    {"2",()=>Ignore()},
                    {"3",()=>DynamicSerializeObject()},
                    {"4",()=>SerializeSelectEnum()},
                };
                dict[input].Invoke();
            }
            Console.ReadKey();
            goto Start;
        }

        private static void SerializeSelectEnum()
        {
            TestEnmu entity = new TestEnmu()
            {
                Type = NotifyType.SMS
            };
            Console.WriteLine(JsonConvert.SerializeObject(entity));
        }

        static void Datatable()
        {
            //序列化DataTable
            DataTable dt = new DataTable();
            dt.Columns.Add("Age", Type.GetType("System.Int32"));
            dt.Columns.Add("Name", Type.GetType("System.String"));
            dt.Columns.Add("Sex", Type.GetType("System.String"));
            dt.Columns.Add("IsMarry", Type.GetType("System.Boolean"));
            for (int i = 0; i < 4; i++)
            {
                DataRow dr = dt.NewRow();
                dr["Age"] = i + 1;
                dr["Name"] = "Name" + i;
                dr["Sex"] = i % 2 == 0 ? "男" : "女";
                dr["IsMarry"] = i % 2 > 0 ? true : false;
                dt.Rows.Add(dr);
            }
            Console.WriteLine(JsonConvert.SerializeObject(dt));
            //
            string json = JsonConvert.SerializeObject(dt);
            dt = JsonConvert.DeserializeObject<DataTable>(json);
            foreach (DataRow dr in dt.Rows)
            {
                Console.WriteLine("{0}\t{1}\t{2}\t{3}\t", dr[0], dr[1], dr[2], dr[3]);
            }
        }

        static void Ignore()
        {
            Person p1 = new Person() { Age = 5, Birthday = default(DateTime), };
            Console.WriteLine(JsonConvert.SerializeObject(p1));
            Person2 p2 = new Person2() { Age = 5, Birthday = default(DateTime), IsMarry = true };
            Console.WriteLine(JsonConvert.SerializeObject(p2));
        }

        static void DynamicSerializeObject()
        {
            Person p = new Person() { Age = 5, Birthday = default(DateTime), IsMarry = false, Name = "rinima" };
            JsonSerializerSettings jsetting = new JsonSerializerSettings();
            jsetting.ContractResolver = new LimitPropsContractResolver(new string[] { "Age", "IsMarry" });
            Console.WriteLine(JsonConvert.SerializeObject(p, Formatting.Indented, jsetting));

        }
    }

    [JsonObject(MemberSerialization.OptIn)]
    public class Person
    {
        public int Age { get; set; }

        /// <summary>
        /// 通过JsonProperty属性设置的方法，可以实现某一属性特别处理的需求，如默认值处理，空值处理，自定义属性名处理，格式化处理。上面空值处理实现
        /// </summary>
        [JsonProperty]
        public string Name { get; set; }

        public string Sex { get; set; }

        /// <summary>
        /// 自定义序列化的字段名称
        /// </summary>
        [JsonProperty(PropertyName = "CName")]
        public bool IsMarry { get; set; }


        [JsonConverter(typeof(ChinaDateTimeConverter))]
        public DateTime Birthday { get; set; }
    }

    [JsonObject(MemberSerialization.OptOut)]
    public class Person2
    {
        public int Age { get; set; }

        public string Name { get; set; }

        public string Sex { get; set; }

        [JsonIgnore]
        public bool IsMarry { get; set; }

        public DateTime Birthday { get; set; }
    }
}
